package com.mpsc.singleton.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.mpsc.singleton.demo.listener.ExcelListener;
import com.mpsc.singleton.demo.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * EasyExcel导入导出
 *
 * @author william@StarImmortal
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    @ApiOperation("写出单元格")
    @GetMapping("/export/user")
    public void exportUserExcel(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("用户列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<UserVo> userList = new ArrayList<>();
            EasyExcel.write(response.getOutputStream()).head(UserVo.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("用户列表")
                    .doWrite(userList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/import/user")
    public void importUserExcel(@RequestPart(value = "file") MultipartFile file) throws IOException {
//        String fileName = "E:\\write.xlsx";//要读excel文件位置
//        EasyExcel.read(fileName,UserVo.class,new ExcelListener()).sheet().doRead();
        List<UserVo> userList = EasyExcel.read(file.getInputStream())
                .head(UserVo.class)
                .registerReadListener(new ExcelListener())
                .sheet()
                .doReadSync();

    }

}
